import QtQuick
import Qt5Compat.GraphicalEffects
import Fk
import Fk.Components.GameCommon as Game

Game.BasicItem {
  id: root

  property int pieceId
  property string name
  property int xPos
  property int yPos
  property int currentGridX: 0
  property int currentGridY: 0
  property int grid: 62
  property bool allowedDrop: false
  property int startX
  property int startY
  property bool dragging: false
  property bool validMove: false

  signal startDragPiece(int pieceId, int xPos, int yPos)
  signal enteredGrid(int pieceId, int gridX, int gridY)
  signal endDragPiece(int pieceId, int xPos, int yPos)

  selectable: true

  width: 62
  height: 62

  // Rectangle {
  //   id: pieceBack
  //   anchors.fill: parent
  //   color: `${((xPos + yPos) % 2 === 0) ? '#a6c2aa76' : '#a6ddddba'}`
  //   opacity: 0.8
  //   visible: root.selected
  // }


  Image {
    id: img
    source: `${Cpp.path}/packages/chess-games/image/nchess/${pieceId < 0 ? "black" : "white"}_${name}.svg`
    sourceSize: Qt.size(200, 200)
    width: 64; height: 64
    anchors.centerIn: parent
    // visible: false
  }

  /*
  ColorOverlay {
    anchors.fill: img
    source: img
    color: root.selectable ? "transparent" : "#5A000000"
  }
  */

  // Image {
  //   source: Cpp.path + "/packages/chess-games/image/nchess/marker.svg"
  //   visible: root.selected
  //   anchors.fill: parent
  // }

  

  MouseArea {
    anchors.fill: parent
    enabled: root.selectable
    cursorShape: Qt.OpenHandCursor
    drag.target: parent
    drag.threshold: 0
    onPressed: function(mouse){
      cursorShape = Qt.ClosedHandCursor
      root.dragging = true
      root.validMove = false
      root.allowedDrop = false
      root.startX = root.x
      root.startY = root.y
      var pos = root.mapToItem(parent.parent, mouse.x, mouse.y)
      root.x = pos.x - root.width / 2
      root.y = pos.y- root.height / 2
      root.z = 6
      root.startDragPiece(root.pieceId, caculatePos(root.x), caculatePos(root.y))
    }
    onPositionChanged: function(mouse) {
      // 拖动过程中 -> 检查是否进入新网格
      var gx = caculatePos(root.x)
      var gy = caculatePos(root.y)

      if (gx !== root.currentGridX || gy !== root.currentGridY) {
        root.currentGridX = gx
        root.currentGridY = gy
        root.enteredGrid(root.pieceId, gx, gy)
      }
    }
    onReleased: function(mouse) {
      cursorShape = Qt.OpenHandCursor
      // 拖动结束 -> 吸附到网格
      var gx = caculatePos(root.x)
      var gy = caculatePos(root.y)
      if (root.allowedDrop) {
        root.validMove = true
      }
      if (root.validMove) {
        root.x = gx * root.grid
        root.y = gy * root.grid
      } else {
        root.x = root.startX
        root.y = root.startY
      }
      root.z = 1
      root.endDragPiece(root.pieceId, caculatePos(root.x), caculatePos(root.y))
      root.dragging = false
    }
    function caculatePos(num) {
      return Math.min(Math.max(Math.round(num / root.grid), 0), 7);
    }
  }
}

